#include "stu_borrow.h"
#include "ui_stu_borrow.h"

stu_borrow::stu_borrow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::stu_borrow),
    borrowface(new borrow)
{
    ui->setupUi(this);

    appDir = QCoreApplication::applicationDirPath();

    createModel();

    loadbookinformation();

    connect(borrowface, &borrow::updataView, this, &stu_borrow::updataView);
    connect(borrowface, &borrow::updataStuBorrowInfo, this, &stu_borrow::updataStuBorrowInfo);
    connect(borrowface, &borrow::handleStuInfo, this, &stu_borrow::handleStuInfo);
}

/* 获取登录学生名字 */
void stu_borrow::getStuname(QString name)
{
    m_who = name;
}

/* 更新列表 */
void stu_borrow::updataView()
{
    clearView();

    QFile file(appDir + "/bookInfo.txt");
    if (file.exists() == false)
    {
        qDebug() << "创建bookInfo文件" << endl;
    }

    file.open(QIODevice::ReadOnly);

    int lineCount = 0;
    char lineBuf[128] = {0};    //读取内容缓存区域
    while (file.atEnd() == false) // 逐行读取文件内容并计数
    {
        file.readLine(lineBuf, sizeof(lineBuf));
        QString data = lineBuf;

        /* 添加一行 */
        int row = model->rowCount();
        model->insertRow(row);  // 插入新的一行

        // 单独设置每个单元格的数据
        QString bookname = data.split("+")[0];
        QStandardItem *booknameItem = new QStandardItem(bookname);
        model->setItem(row, 0, booknameItem);

        QString author = data.split("+")[1];
        QStandardItem *authorItem = new QStandardItem(author);
        model->setItem(row, 1, authorItem);

        QString cnt = data.split("+")[2].split("\n")[0];
        QStandardItem *cntItem = new QStandardItem(cnt);
        model->setItem(row, 2, cntItem);

        lineCount++;
    }
    file.close();
}

/* 点击借阅书籍按钮 */
void stu_borrow::on_borrowBtn_clicked()
{
    borrowface->show();
}

/* 更新学生借书信息 */
void stu_borrow::updataStuBorrowInfo(QString bookname, QString author)
{
    QFile file(appDir + "/" + m_who + ".txt");

    if (file.exists() == false)
    {
        qDebug() << "创建新文件" << endl;
    }

    file.open(QIODevice::Append);

    QTextStream out(&file);
    // 设置编码为 UTF-8
    out.setCodec("UTF-8");

    out << bookname;
    out << "+";
    out << author;
    out << "\n";

    file.close();
}

/* 处理学生信息 */
void stu_borrow::handleStuInfo()
{
    QFile file(appDir + "/stuInfo.txt");
    if (file.exists() == false)
    {
        qDebug() << "创建stuInfo文件" << endl;
    }

    file.open(QIODevice::ReadOnly);

    QStringList lines;  //字符串链表

    while (file.atEnd() == false) //文件没结束
    {
        QString line = file.readLine(); // 读取每一行字符串
        lines.append(line);    //读取每一行字符串到链表中
    }
    file.close();

    // 查找并修改目标行
    bool found = false;
    for (int i = 0; i < lines.size(); ++i)
    {
        QString data = lines[i];
        if (lines[i].split("+")[0] == m_who)
        {
            QString cnt = lines[i].split("+")[3].split("\n")[0];
            cnt = QString::number(cnt.toInt() + 1);
            qDebug() << "借了几本书" << cnt << endl;
            lines[i] = lines[i].split("+")[0] + "+" + lines[i].split("+")[1] + "+" + lines[i].split("+")[2] + "+" + cnt + "\n"; // 修改该行
            found = true;
            break; // 只需要修改第一个匹配项
        }
    }

    if (!found) //没找到
    {
        QMessageBox::warning(this, "借阅失败", "该学生不存在");
        return;
    }

    file.open(QIODevice::WriteOnly);

    QTextStream out(&file);
    // 设置编码为 UTF-8
    out.setCodec("UTF-8");
    for (int idx = 0; idx < lines.size(); idx++)
    {
        out << lines[idx];
    }

    file.close();
}

/* 创建模型 */
void stu_borrow::createModel()
{
    model = new QStandardItemModel(0, 3);
    model->setHorizontalHeaderItem(0, new QStandardItem("书名"));
    model->setHorizontalHeaderItem(1, new QStandardItem("作者"));
    model->setHorizontalHeaderItem(2, new QStandardItem("图书数量"));

    ui->tableView->setModel(model);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}

/* 加载图书信息 */
void stu_borrow::loadbookinformation()
{
    QFile file(appDir + "/bookInfo.txt");
    if (file.exists() == false)
    {
        qDebug() << "创建bookInfo文件" << endl;
    }

    file.open(QIODevice::ReadOnly);

    int lineCount = 0;
    char lineBuf[128] = {0};    //读取内容缓存区域
    while (file.atEnd() == false) // 逐行读取文件内容并计数
    {
        file.readLine(lineBuf, sizeof(lineBuf));
        QString data = lineBuf;

        /* 添加一行 */
        int row = model->rowCount();
        model->insertRow(row);  // 插入新的一行

        // 单独设置每个单元格的数据
        QString bookname = data.split("+")[0];
        QStandardItem *booknameItem = new QStandardItem(bookname);
        model->setItem(row, 0, booknameItem);

        QString author = data.split("+")[1];
        QStandardItem *authorItem = new QStandardItem(author);
        model->setItem(row, 1, authorItem);

        QString cnt = data.split("+")[2].split("\n")[0];
        QStandardItem *cntItem = new QStandardItem(cnt);
        model->setItem(row, 2, cntItem);

        lineCount++;
    }
    file.close();
}

/* 清空表格数据 */
void stu_borrow::clearView()
{
    int rowCount = model->rowCount();
    int columnCount = model->columnCount();

    // 清除所有单元格的内容
    for (int row = 0; row < rowCount; ++row)
    {
        for (int col = 0; col < columnCount; ++col)
        {
            if (model->item(row, col))
            {
                model->setItem(row, col, new QStandardItem());
            }
        }
    }

    // 如果有必要，可以调整行数到零
    model->setRowCount(0);
}

stu_borrow::~stu_borrow()
{
    delete ui;
}
